using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Net.Http;
using NetCoreAudio;
using Newtonsoft.Json.Linq;
using PddWebAuto.Helper;
using PddWebAuto.Model;
using PddWebAuto.PddModel;
using PddWebAuto.PddSearch;
using PddWebAuto.SmsHandler;
using PuppeteerSharp;
using PuppeteerSharp.Input;
using Point = OpenCvSharp.Point;

namespace PddWebAuto
{
    public class ChromeDrive : IDisposable
    {
        public const int MOUSEEVENTF_LEFTDOWN = 0x02;
        public const int MOUSEEVENTF_LEFTUP = 0x04;
        public static string ChromePath = "";
        private bool _autoSaveCookieState_;
        private IBrowser _browser;
        private string _error = "";
        private readonly Action<string> _logEvent;
        private bool _success = false;
        public IPage _currentPage;
        public int _DetailError;
        private string _proxyIPEndPoint;
        private readonly Random _random = new Random(DateTime.Now.Millisecond);
        public Process ChromeProcess;
        private GroupItemModel ItemModel;
        private int RemotePort;
        public string SmsCaptcha;

        /// <summary>
        /// 当前的浏览器分组
        /// </summary>
        public GroupModel Group { get; set; }

        /// <summary>
        /// 采集使用属性（是否忙碌中)
        /// </summary>
        public bool Busy { get; set; }

        public ChromeDrive(Action<string> LogCall, GroupModel groupModel)
        {
            _logEvent = LogCall;
            Group = groupModel;
        }

        public void Dispose()
        {
            if (_browser == null)
            {
                return;
            }

            try
            {
                _browser.CloseAsync();
                _browser.Dispose();
            }
            catch (Exception)
            {
                // ignored
            }
        }

        [DllImport("user32.dll")]
        private static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        public void Log(string t)
        {
            _logEvent?.Invoke("[" + ItemModel.Title + "] " + t);
            Debug.WriteLine(t);
        }

        private string GetChromeWsAddress(int Port)
        {
            //
            var Item = new HttpItem();
            Item.URL = "http://127.0.0.1:" + Port + "/json/version";
            var Res = Item.Send();
            if (Res.IsSuccessStatusCode)
            {
                var webSocketDebuggerUrl =
                    Regex.Match(Res.Html, "\"webSocketDebuggerUrl\": \"([\\s\\S]*?)\"")?.Groups[1]?.Value ?? "";
                return webSocketDebuggerUrl;
            }

            return "";
        }

        /// <summary>
        ///     获取可用端口
        /// </summary>
        /// <returns></returns>
        private static int FreeTcpPort(int level = 0)
        {
            try
            {
                if (level >= 10) return -1;
                var tcpListener = new TcpListener(IPAddress.Any, 0);
                tcpListener.Start();
                var port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;
                tcpListener.Stop();
                return port;
            }
            catch (Exception)
            {
                level++;
                return FreeTcpPort(level);
            }
        }

        public string GetCommonParam()
        {
            var Data =
                $"deviceMemory={ItemModel.deviceMemory}&platform=Win32&colorDepth={ItemModel.colorDepth}&pixelDepth={ItemModel.pixelDepth}&screenWidth={ItemModel.screenSize.Split('x')[0]}&screenHeight={ItemModel.screenSize.Split('x')[1]}&hardwareConcurrency={ItemModel.hardwareConcurrency}&abname={Convert.ToBase64String(Encoding.UTF8.GetBytes(ItemModel.Title))}&gpuRenderer={ItemModel.gpuRenderer}&gpuVendor=Google Inc.&geolocation=no&productSub=20030107&vendor=Google Inc.&languages={ItemModel.languages}&timezone={ItemModel.timezone}&font=cmFuZG9t&macAddress={ItemModel.macAddress}&computerName={ItemModel.computerName}&userName={ItemModel.userName}&speechVoices={Convert.ToBase64String(Encoding.UTF8.GetBytes(ItemModel.speechVoices))}&&filterPixel=1";
#if !DEBUG
            Data += "&disconsole=1&";
#endif
            //
            if (!string.IsNullOrEmpty(_proxyIPEndPoint))
            {
                Data = $"ipAddress={_proxyIPEndPoint.Split(':')[0]}&" + Data;
            }

            return Data;
        }

        private string GetArgs(bool proxyEnable)
        {
            var Args = new List<string>();
            Args.Add("--args");
            Args.Add("--user-data-dir=\"" + AppClass.GetChromeDataPath(ItemModel.ChromeData) + "\"");
            if (proxyEnable && !string.IsNullOrEmpty(_proxyIPEndPoint))
            {
                Log("正在使用代理IP:" + _proxyIPEndPoint);

                Args.Add("--proxy-server=" + _proxyIPEndPoint);
            }

            Args.Add("--disable-d3d11");
            Args.Add("--disable-dwm-composition");
            Args.Add("--disable-legacy-window");
            Args.Add("--lang=zh-CN");
            Args.Add("--user-agent=\"" + ItemModel.userAgent + "\"");
            if (!string.IsNullOrEmpty(ItemModel.windowSize))
            {
                Args.Add("--window-size=\"" + ItemModel.windowSize.Replace("x", ",") + "\"");
            }

            Args.Add("--new-window");
            Args.Add("--disable-features=\"UserAgentClientHint,ExtensionsToolbarMenu,FlashDeprecationWarning,\"");
            Args.Add("--enable-media-stream");
            Args.Add("--audio-output-num=1");
            Args.Add("--video-intput-num=1");
            Args.Add("--enable-speech-input");
            Args.Add("--profile-directory=\"UserDefault\"");
            Args.Add("--browser-rand-hash=\"" + ItemModel.fingerprintRandom + "\"");
            Args.Add("--plugins=\"" + ItemModel.plugins + "\"");
#if !DEBUG
            Args.Add("--devtools-flags=\"no\"");
#endif
            Args.Add("--plugins=\"" + ItemModel.plugins + "\"");
            if (!string.IsNullOrEmpty(ItemModel.position))
            {
                Args.Add("--window-position=\"" + _random.Next(30) + "," + _random.Next(10) + "\"");
            }

            Args.Add("--browser-common-param=\"" + GetCommonParam() + "\"");
            Args.Add("--remote-debugging-port=" + RemotePort);
            return string.Join(" ", Args.ToArray()).Trim();
        }

        private DateTime _lastRequestTime = DateTime.Now;

        /// <summary>
        /// 在指定时间内是否发生过网络请求
        /// </summary>
        /// <returns></returns>
        private bool InTimeHaveRequest()
        {
            if ((DateTime.Now - _lastRequestTime).TotalMilliseconds <= 2500)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="m"></param>
        /// <param name="proxy"></param>
        /// <param name="proxyEnable"></param>
        /// <returns></returns>
        public async Task<bool> RunChromeProcessAsync(GroupItemModel m, string proxy, bool proxyEnable = false)
        {
            ItemModel = m;
            Log("启动浏览器中...");
            RemotePort = FreeTcpPort();
            var info = new ProcessStartInfo
            {
                FileName = Path.Combine(ChromePath, "chrome.exe")
            };
            _proxyIPEndPoint = proxy;
            info.Arguments = GetArgs(proxyEnable) + " https://mobile.yangkeduo.com/";
            info.UseShellExecute = false;
            var tryCount = 0;
            retry:
            tryCount++;
            ChromeProcess = Process.Start(info);
            await TaskHelper.Delay(1000 * 3);
            var options = new ConnectOptions
            {
                BrowserWSEndpoint = GetChromeWsAddress(RemotePort),
                DefaultViewport = null
            };
            try
            {
                _browser = await Puppeteer.ConnectAsync(options);
                _browser.IgnoreHTTPSErrors = true;
                var Pages = await _browser.PagesAsync();
                _currentPage = Pages[0];
                await _currentPage.SetRequestInterceptionAsync(true);
                _currentPage.Request += (sender, e) =>
                {
                    _lastRequestTime = DateTime.Now;
                    e.Request.ContinueAsync();
                };
                _currentPage.DOMContentLoaded += async (k, j) =>
                {
                    try
                    {
                        await _currentPage.PaddEnhanceCookies();
                        if (!_autoSaveCookieState_)
                        {
                            Debug.WriteLine("处理保存");
                            if (await AutoSaveCookies())
                            {
                                Debug.WriteLine("自动保存成功");
                                _autoSaveCookieState_ = true;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                };
                Log("启动成功");
                return true;
            }
            catch (Exception ex)
            {
                if (tryCount <= 3)
                {
                    if (ChromeProcess != null && !ChromeProcess.HasExited)
                    {
                        try
                        {
                            ChromeProcess.Kill();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }

                    goto retry;
                }

                Log(ex.Message);
                if (ChromeProcess != null && !ChromeProcess.HasExited)
                {
                    ChromeProcess.Kill();
                }
            }

            Log("启动失败");
            return false;
        }

        /// <summary>
        ///     验证当前是否有效
        /// </summary>
        /// <returns></returns>
        public bool Valid()
        {
            return ChromeProcess != null && !ChromeProcess.HasExited;
        }

        private void WorkRandomSleep(int start = 1000, int end = 1500)
        {
            TaskHelper.Delay(_random.Next(start, end)).Wait();
            // Thread.Sleep(_random.Next(start, end));
        }

        public async Task<string> Login(ISMSAPI Sms)
        {
            var tryCount = 0;
            retryLogin:
            tryCount++;
            if (!await _currentPage.MyGoToAsync(this.ChromeProcess,
                    "https://mobile.yangkeduo.com/personal.html?refer_page_name=login"))
            {
                if (tryCount > 4)
                {
                    return "登陆失败";
                }

                goto retryLogin;
            }

            if (await _currentPage.MyWaitSelector(".phone-login", null) ||
                await _currentPage.MyWaitSelector("#captcha-btn", null))
            {
                WorkRandomSleep(1500, 2000);

                if (await _currentPage.MySelectorClick(".phone-login"))
                {
                    WorkRandomSleep();
                }

                var opacity =
                    await _currentPage.EvaluateExpressionAsync<string>(
                        "document.querySelector(\"#first\").style.opacity");

                if (opacity == "")
                {
                    await _currentPage.MySelectorClick(".phone-login");
                    WorkRandomSleep(1500, 2000);
                }

                Log("获取手机号码");
                string telPhone = null;
                try
                {
                    telPhone = await Sms.GetPhone();
                }
                catch (TaskCanceledException)
                {
                    return "任务已取消";
                }
                catch (Exception ex)
                {
                    Log("GetPhone: " + ex.Message);
                }

                if (string.IsNullOrEmpty(telPhone))
                {
                    return "手机号码获取为空:" + Sms.GetMsg();
                }

                Log("手机号码:" + telPhone);
                await _currentPage.MySelectorInputAndFocus("#user-mobile", telPhone, true);
                WorkRandomSleep();
                await _currentPage.MySelectorInputAndFocus("#phone-number", telPhone, true);
                WorkRandomSleep(1500, 2000);
                await _currentPage.MySelectorClick("#code-button");
                WorkRandomSleep(1500, 2000);
                await _currentPage.MySelectorClick("#captcha-btn");
                WorkRandomSleep(1500, 2000);
                if (await VerificationHanlder())
                {
                    goto retryLogin;
                }

                Log("等待短信");
                SmsCaptcha = await Sms.WaitSms(90, telPhone);
                if (string.IsNullOrEmpty(SmsCaptcha))
                {
                    return "短信获取错误:" + Sms.GetMsg();
                }

                Log("短信:" + SmsCaptcha);
                await _currentPage.MySelectorInputAndFocus("#input-code", SmsCaptcha);
                WorkRandomSleep();
                await _currentPage.MySelectorInputAndFocus("#captcha", SmsCaptcha);
                WorkRandomSleep(1500, 2000);
                await _currentPage.MySelectorClick("#submit-button");
                await _currentPage.MySelectorClick("#submit-btn");
                WorkRandomSleep(1000, 1100);
                if (InTimeHaveRequest())
                {
                    //等待网络加载完毕
                    await _currentPage.MyWaitLoadingCompleted(ChromeProcess, async () =>
                    {
                        await _currentPage.MySelectorClick("#submit-button");
                        await _currentPage.MySelectorClick("#submit-btn");
                    });
                }

                if (await VerificationHanlder())
                {
                    //验证码检测处理
                }

                if (!_currentPage.Url.Contains("login.html"))
                {
                    var accessToken = await _currentPage.EvaluateExpressionAsync<string>("document.cookie");
                    if (string.IsNullOrEmpty(accessToken))
                    {
                        if (InTimeHaveRequest())
                        {
                            await _currentPage.MyWaitLoadingCompleted();
                        }

                        accessToken = await _currentPage.EvaluateExpressionAsync<string>("document.cookie");
                    }

                    if (accessToken.Contains("PDDAccessToken"))
                    {
                        try
                        {
                            await _currentPage.ReloadAsync();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }

                        WorkRandomSleep(3000, 5000);
                        Log("登陆账户成功");
                        return "OK";
                    }
                }
                else
                {
                    return "登录失败:" + _currentPage.Url;
                }
            }
            else
            {
                if (await _currentPage.MySelectorIsExist(".order-shipping"))
                {
                    Log("浏览器已有登陆账户");
                    return "OK";
                }
            }

            return "登陆失败";
        }

        /// <summary>
        ///     检测全部订单是否有订单
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CheckExistOrder()
        {
            Log("检查老号");
            Start:
            if (await _currentPage.MySelectorClick(".alert-goto-app-cancel"))
            {
                WorkRandomSleep();
            }

            if (await _currentPage.MyWaitSelector(".order-menu .order-title .others",
                    async () => { await _currentPage.MySelectorClick(".alert-goto-app-cancel"); }, 3))
            {
                await _currentPage.MySelectorClick(".order-menu .order-title .others");
            }
            else
            {
                await _currentPage.MyGoToAsync(this.ChromeProcess,
                    "https://mobile.yangkeduo.com/orders.html?type=0&comment_tab=1&combine_orders=1&main_orders=1&refer_page_name=personal");
            }

            WorkRandomSleep(3000, 5000);
            if (await VerificationHanlder())
            {
                goto Start;
            }

            for (var i = 0; i < 3; i++)
            {
                try
                {
                    var Count = await _currentPage.EvaluateExpressionAsync<int>(
                        "document.querySelector(\".react-base-list\").childElementCount");
                    if (Count <= 0)
                    {
                        return false;
                    }

                    Log("正在清理账户的Cookie");
                    if (_currentPage.Target != null)
                    {
                        var session = await _currentPage.Target.CreateCDPSessionAsync();
                        await session.SendAsync("Network.clearBrowserCookies");
                    }

                    await _currentPage.DeleteCookieAsync();
                    Log("账户Cookie清理完成");
                    return true;
                }
                catch (Exception)
                {
                    WorkRandomSleep(2000, 3000);
                }
            }

            Log("检测老号订单列表超出次数");
            return true;
        }

        /// <summary>
        ///     关闭钱包
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ClosePddWallet()
        {
            Log("关闭钱包");
            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/sub_select_account.html?from_scene=DKQD&qbf_page=dkqd&_pdd_fs=1&refer_page_name=selfsv_answer");
            WorkRandomSleep(2000, 3000);
            if (await VerificationHanlder())
            {
                goto Start;
            }

            var Xpath = "//div[contains(text(),\"订单对应的支付账户\")]";
            if (await _currentPage.MyWaitXPath(Xpath))
            {
                await _currentPage.MyXpathClick(Xpath);
                WorkRandomSleep(1500, 2500);
                Xpath = "//div[contains(text(),\"仍旧更换\")]";
                await _currentPage.MyXpathClick(Xpath);
                WorkRandomSleep();
                await _currentPage.MySelectorClick("[data-active=\"red\"]");
                WorkRandomSleep(1000, 1100);
                if (InTimeHaveRequest())
                {
                    await _currentPage.MyWaitLoadingCompleted(ChromeProcess,
                        async () =>
                        {
                            await _currentPage.MyXpathClick(Xpath);
                            WorkRandomSleep();
                            await _currentPage.MySelectorClick("[data-active=\"red\"]");
                        },
                        4 * 1000);
                }

                //sub_select_account
                return !_currentPage.Url.Contains("sub_select_account");
            }

            return false;
        }

        /// <summary>
        ///     检测是否登陆页面
        /// </summary>
        /// <returns></returns>
        public async Task<bool> IsLogin()
        {
            try
            {
                return _currentPage.Url.Contains("login.html") ||
                       (await _currentPage.MyGetHtml()).Contains("id=\"login\"");
            }
            catch (Exception)
            {
            }

            return false;
        }

        /// <summary>
        ///     是需要验证码
        /// </summary>
        /// <returns></returns>
        public async Task<bool> IsVerification()
        {
            try
            {
                return _currentPage.Url.Contains("psnl_verification.html") ||
                       (await _currentPage.MyGetHtml()).Contains("安全验证");
            }
            catch (Exception)
            {
            }

            return false;
        }

        /// <summary>
        ///     验证码处理
        /// </summary>
        /// <returns></returns>
        public async Task<bool> VerificationHanlder()
        {
            if (await IsVerification())
            {
                WorkRandomSleep(2000, 5000);
                var el = await _currentPage.MyGetSelectorAndVisible("intel-btn");
                if (el != null)
                {
                    await _currentPage.MyClick(el);
                }

                Log("拖动验证码处理");
                var _start = DateTime.Now;
                var tryCount = 0;
                while (await IsVerification())
                {
                    tryCount++;
                    if (tryCount > 3)
                    {
                        //播放声音
                        try
                        {
                            await new Player().Play("notify.mp3");
                            await TaskHelper.Delay(5000);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }

                        await TaskHelper.Delay(10000);
                        continue;
                    }

                    var slideBtnHold = false;
                    if (await _currentPage.QuerySelectorAsync("img.slider-img-bg") != null &&
                        await _currentPage.QuerySelectorAsync("div.slide-btn") != null)
                    {
                        await _currentPage.MyWaitSelector("img.slider-img-bg", null);
                        var Start_Y = _random.Next(10, 30);
                        var Start_X = _random.Next(10, 30);
                        if (await _currentPage.QuerySelectorAsync("img.block-img") == null)
                        {
                            Log("处理隐藏验证码...");
                            slideBtnHold = true;
                            var slideBtn = await _currentPage.MyGetSelectorAndVisible("div.slide-btn");
                            var BoundingBox = await slideBtn.BoundingBoxAsync();
                            await _currentPage.Mouse.MoveAsync(BoundingBox.X + Start_X, BoundingBox.Y + Start_Y);
                            WorkRandomSleep(100, 200);
                            await _currentPage.Mouse.DownAsync(new ClickOptions
                                { Button = MouseButton.Left, ClickCount = 1, Delay = 5 });
                            WorkRandomSleep();
                            //mouses.Add(new MouseData() { Action = MouseData.ActionEnum.Left_Hold, X = Start_X, Y = Start_Y, Delay = ran.Next(500, 1000) });
                            //slideBtn.MouseAction(mouses, 0, 0).Wait();
                            if (await _currentPage.QuerySelectorAsync("img.block-img") == null)
                            {
                                await TaskHelper.Delay(4 * 1000);
                                continue;
                            }
                        }

                        var src =
                            await (await _currentPage.MyGetSelectorAndVisible("img.slider-img-bg")).MyAttrSting("src");
                        src = src.Substring(22);
                        //背景图
                        var bg = Convert.FromBase64String(src);
                        src = await (await _currentPage.MyGetSelectorAndVisible("img.block-img")).MyAttrSting("src");
                        src = src.Substring(22);
                        //滑块图
                        var block = Convert.FromBase64String(src);

                        var EndXY = new Point();
                        var sliderBgRect = await (await _currentPage.MyGetSelectorAndVisible("img.slider-img-bg"))
                            .BoundingBoxAsync();
                        var BgRect = new Rectangle((int)sliderBgRect.X, (int)sliderBgRect.Y,
                            (int)sliderBgRect.Width, (int)sliderBgRect.Height);
                        var sliderImgRect =
                            await (await _currentPage.MyGetSelectorAndVisible("img.block-img")).BoundingBoxAsync();
                        var ImgRect = new Rectangle((int)sliderImgRect.X, (int)sliderImgRect.Y,
                            (int)sliderImgRect.Width, (int)sliderImgRect.Height);

                        var verify = await SliderVerify.verify(bg, block, BgRect, ImgRect);
                        if (verify.Item1)
                        {
                            EndXY = verify.Item2;

                            if (EndXY.X < 100)
                            {
                                await _currentPage.MySelectorClick("div.refresh");
                                await TaskHelper.Delay(3 * 1000);
                                continue;
                            }

                            Log("拖动中...");

                            var _Y = Start_Y;
                            var _X = Start_X;
                            await TaskHelper.Delay(1000);
                            var El = await _currentPage.MyGetSelectorAndVisible("div.slide-btn");
                            if (El == null)
                            {
                                await TaskHelper.Delay(3 * 1000);
                                continue;
                            }

                            var slideBtnRect = await El.BoundingBoxAsync();

                            EndXY.X += _X; //起始偏移补偿
                            var RanY = _Y;
                            if (!slideBtnHold)
                            {
                                await _currentPage.Mouse.MoveAsync(slideBtnRect.X + _X, slideBtnRect.Y + RanY);
                                WorkRandomSleep(100, 200);
                                await _currentPage.Mouse.DownAsync(new ClickOptions
                                    { Button = MouseButton.Left, ClickCount = 1, Delay = 5 });
                                WorkRandomSleep();
                            }

                            var minute = _random.Next(6, 8);
                            for (var i = _X; i < EndXY.X; i++)
                            {
                                await _currentPage.Mouse.MoveAsync(slideBtnRect.X + i, slideBtnRect.Y + RanY);
                                WorkRandomSleep(4, 8);
                                if (i > EndXY.X / minute)
                                {
                                    i += _random.Next(2);
                                }

                                if (i > EndXY.X / 4)
                                {
                                    RanY = _Y + _random.Next(2);
                                }
                            }

                            WorkRandomSleep(100, 200);
                            await _currentPage.Mouse.UpAsync();
                            Log("拖动结束");
                            await TaskHelper.Delay(1000 * 4);
                            if (_currentPage.Url.Contains("psnl_verification.html"))
                            {
                                Log("拖动失败3秒钟后继续拖动");
                                await TaskHelper.Delay(1000 * 4);
                            }
                            else
                            {
                                return true;
                            }
                        }
                        else
                        {
                            Log("识别失败自动刷新.");
                            await TaskHelper.Delay(1000 * 2);
                            await _currentPage.ReloadAsync();
                            await TaskHelper.Delay(1000 * 2);
                        }
                    }
                    else
                    {
                        await _currentPage.MySelectorClick(".intel-btn");
                    }

                    await _currentPage.MyWaitLoadingCompleted(null, null, 2000);
                }

                return true;
            }

            return false;
        }


        public async Task<List<OrderGoodsModel>> OrderExportTask()
        {
            Log("进入订单列表");
            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/orders.html?type=0&comment_tab=1&combine_orders=1&main_orders=1&refer_page_name=personal&refer_page_id=&refer_page_sn=10001");
            if (await VerificationHanlder())
            {
                goto Start;
            }

            if (await IsLogin())
            {
                Log("账户登陆失效");
                return null;
            }

            var OrderGoods = new List<OrderGoodsModel>();
            var el = await _currentPage.MyGetSelectorAndVisible(".deal-list-status-new .react-base-list-wrapper");
            if (el == null)
            {
                Log("订单列表元素为空!");
                if ((await _currentPage.MyGetHtml()).Contains("您还没有相关的订单"))
                {
                    return OrderGoods;
                }

                return null;
            }

            string hasLoadedAll = null;
            var Itemi = 0;
            do
            {
                hasLoadedAll = await _currentPage.MyReact(".deal-list-status-new .react-base-list-wrapper",
                    "state.hasLoadedAll");
                var list = await _currentPage.MyReact(".deal-list-status-new .react-base-list-wrapper", "state.list");
                if (!string.IsNullOrEmpty(list))
                {
                    var JsonList = JArray.Parse(list);
                    if (JsonList.Count > 0)
                    {
                        for (var i = Itemi; i < JsonList.Count; i++)
                        {
                            var m = new OrderGoodsModel();
                            //m.PDDAccessToken = AccessToken;
                            m.OrderSn = (string)JsonList[i]["orderSn"];
                            m.goodsName = (string)JsonList[i].SelectToken("orderGoods[0].goodsName");
                            m.GoodsId = (string)JsonList[i].SelectToken("orderGoods[0].goodsId");
                            m.OrderAmount = (string)JsonList[i].SelectToken("orderAmount");
                            m.OrderStatus = (string)JsonList[i].SelectToken("orderStatusPrompt");
                            m.SkuId = (string)JsonList[i].SelectToken("orderGoods[0].skuId");
                            m.Suffix = (string)JsonList[i].SelectToken("priceDesc.suffix");
                            m.MallName = (string)JsonList[i].SelectToken("mall.mallName");
                            m.SkuSpec = (string)JsonList[i].SelectToken("orderGoods[0].spec");

                            OrderGoods.Add(m);
                            Debug.WriteLine(m.OrderSn);
                            Itemi = i + 1;
                        }

                        var item = await _currentPage.QuerySelectorAsync(
                            ".deal-list-status-new .react-base-list-wrapper .react-base-list>div[data='" +
                            (JsonList.Count - 1) + "']");
                        if (item != null)
                        {
                            await item.MyScrollIntoView();
                        }
                    }
                }

                await _currentPage.MySelectorWheel(".deal-list-status-new .react-base-list-wrapper .react-base-list",
                    _random.Next(60, 150), 160);
                WorkRandomSleep(1000, 1100);
                if (InTimeHaveRequest())
                {
                    await _currentPage.MyWaitLoadingCompleted(ChromeProcess, async () =>
                    {
                        await _currentPage.MySelectorWheel(
                            ".deal-list-status-new .react-base-list-wrapper .react-base-list",
                            _random.Next(60, 150), 160);
                    }, 5000);
                }

// #if DEBUG
//                 if (Itemi > 5)
//                 {
//                     break;
//                 }
// #endif

                if ((await _currentPage.MyGetHtml()).Contains("您已经没有更多的订单了") ||
                    (await _currentPage.MyGetHtml()).Contains("您还没有相关的订单"))
                {
                    break;
                }

                if (Program._Run_ != 1)
                {
                    return null;
                }
            } while (hasLoadedAll != null && hasLoadedAll.Contains("false"));

            if (Program._Run_ != 1)
            {
                return null;
            }

            Log("订单列表获取共计:" + OrderGoods.Count + "条");
            foreach (var item in OrderGoods)
            {
                await My_Order(item);
            }

            return OrderGoods;
        }

        /// <summary>
        ///     上传单号
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<bool> UploadOrderTrackingTask(UploadOrderTrackingModel m)
        {
            Log("进入上传物流信息页面:" + m.order_sn);
            Start:
            //https://mobile.yangkeduo.com/complaint_detail.html?after_sales_id=19154865761&order_sn=221113-543267255062940&refer_page_name=order_detail&refer_page_id=10038_1668957648595_aog2p6kv8j&refer_page_sn=10038
            //https://mobile.yangkeduo.com/complaint.html?mode=128&after_sales_id=19154865761&order_sn=221113-543267255062940&refer_page_name=complaints_new_detail&refer_page_id=82697_1668957653280_kn7x9z5vu4&refer_page_sn=82697
            //https://mobile.yangkeduo.com/complaint.html?mode=128&after_sales_id=19154865761&order_sn=221113-543267255062940&refer_page_name=complaints_new_detail&refer_page_id=82697_1668957806908_ibvc6h752l&refer_page_sn=82697
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/complaint_detail.html?order_sn=" + m.order_sn +
                "&after_sales_id=" + m.salesId +
                "&refer_page_name=order_detail&refer_page_id=10038_" +
                HttpHelper.TimeStampMilliseconds() + "_aog2p6kv8j&refer_page_sn=10038");
            if (await VerificationHanlder())
            {
                goto Start;
            }

            if (await IsLogin())
            {
                Log("账户登陆失效");
                return false;
            }

            var ElXpath = "//div[contains(text(),\"去填单号\")]";
            if (await _currentPage.MyWaitXPath(ElXpath))
            {
                var el = await _currentPage.MyGetXPath(ElXpath);
                await el.MyScrollIntoView();
                await el.MyClick();
                WorkRandomSleep(1500, 2000);
            }

            ElXpath = "//div[contains(text(),\"填写快递单号\")]";

            if (await _currentPage.MyWaitXPath(ElXpath))
            {
                var el = await _currentPage.MyGetXPath(ElXpath);
                await el.MyScrollIntoView();
                await el.MyClick();
                WorkRandomSleep(2000, 3000);
                await _currentPage.MyWaitLoadingCompleted(null, null, 5 * 1000);
            }

            if ((await _currentPage.MyGetHtml()).Contains("待商家收货"))
            {
                Log("当前订单单号已上传");
                return true;
            }

            if ((await _currentPage.MyGetHtml()).Contains("无法发起售后申请"))
            {
                Log("无法发起售后申请");
                return false;
            }

            if (!await _currentPage.MyWaitSelector("#as-input-track-number", null, 5))
            {
                Log("等待物流输入框加载超时!");
                return false;
            }

            WorkRandomSleep();
            await _currentPage.MySelectorInputAndFocus("#as-input-track-number", m.tracking, true);
            WorkRandomSleep(2000, 5000);
            if ((await _currentPage.MyGetHtml()).Contains("未匹配到快递公司"))
            {
                Log("快递单号公司无法定位");
                return false;
            }

            if ((await _currentPage.MyGetHtml()).Contains("请填写实际支付的运费总额") ||
                (await _currentPage.MyGetHtml()).Contains("as-input-delivery-fee"))
            {
                Log("填写运费:(" + m.Freight + ")");
                await _currentPage.MySelectorInputAndFocus("#as-input-delivery-fee", m.Freight, true);
                WorkRandomSleep();
            }

            await _currentPage.MySelectorInputAndFocus("#as-description .textarea", m.Directions, true);
            WorkRandomSleep(2000, 3000);
            var El = await _currentPage.QuerySelectorAsync(".submit-btn button");
            if (El == null)
            {
                Log("提交按钮检测不到");
                return false;
            }

            await El.MyScrollIntoView();
            await El.MyClick();
            WorkRandomSleep(2000, 3000);
            await _currentPage.MyWaitLoadingCompleted(null, null, 5 * 1000);
            if ((await _currentPage.MyGetHtml()).Contains("待商家收货"))
            {
                Log("上传单号成功");
                return true;
            }

            Log("上传单号失败");
            return false;
        }

        /// <summary>
        ///     退货退款
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ReturnsGoodsTask(ReturnsGoodsInfoModel m)
        {
            Log("进入退单页面:" + m.order_sn);
            var Url = "";
            //after_sales_type 退款类型
            if (m.IsRefunds)
            {
                //仅退款
                //user_ship_status=1 未收到货 退款不退货
                Url = "https://mobile.yangkeduo.com/complaint.html?order_sn=" + m.order_sn +
                      "&refer_page_name=my_order&refer_page_id=10032_" + HttpHelper.TimeStampMilliseconds() +
                      "_g6qy0096op&refer_page_sn=10032&after_sales_reason=0&after_sales_type=1&user_ship_status=1";
            }
            else
            {
                //退货退款
                Url = "https://mobile.yangkeduo.com/complaint.html?order_sn=" + m.order_sn +
                      "&refer_page_name=my_order&refer_page_id=10032_" + HttpHelper.TimeStampMilliseconds() +
                      "_g6qy0096op&refer_page_sn=10032&after_sales_reason=0&after_sales_type=2";
            }

            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess, Url);
            if (await VerificationHanlder())
            {
                goto Start;
            }

            if (await IsLogin())
            {
                Log("账户登陆失效");
                return false;
            }

            if ((await _currentPage.MyGetHtml()).Contains("您已申请过售后"))
            {
                Log("您已申请过售后，正在处理中");
                return true;
            }

            if ((await _currentPage.MyGetHtml()).Contains("无法发起售后申请"))
            {
                Log("无法发起售后申请");
                return false;
            }

            await _currentPage.MySelectorClick("#as-reason .select-container");
            if (!await _currentPage.MyWaitSelector("#as-reason-options .as-show-popup",
                    async () => { await _currentPage.MySelectorClick("#as-reason .select-container"); }, 3))
            {
                Log("等待申请原因超时");
                return false;
            }

            var lis = await _currentPage.QuerySelectorAllAsync("#as-reason-options .as-show-popup li");
            IElementHandle El = null;
            foreach (var item in lis)
            {
                if ((await item.MyTextContent()).Contains(m.Reason))
                {
                    Log("理由:" + await item.MyTextContent());
                    El = item;
                    await El.MyScrollIntoView();
                    break;
                }
            }

            if (El == null)
            {
                Log("未找到申请理由:" + m.Reason);
                return false;
            }

            await El.MyClick();
            WorkRandomSleep();
            await _currentPage.MySelectorInputAndFocus("#as-description textarea", m.Directions, true);
            await TaskHelper.Delay(1000);
            await _currentPage.MySelectorInputAndFocusAndRetry("#as-input-as-mobile", m.Phone, true);
            WorkRandomSleep(2000, 3000);
            El = await _currentPage.MyGetSelectorAndVisible(".submit-btn button");
            await El.MyClick();
            WorkRandomSleep(1000, 1100);
            if (InTimeHaveRequest())
            {
                await _currentPage.MyWaitLoadingCompleted(ChromeProcess, async () => { await El.MyClick(); });
            }

            if (_currentPage.Url.Contains("complaint_detail.html"))
            {
                Log("申请成功");
                return true;
            }

            Log("申请失败");
            return false;
        }

        /// <summary>
        ///     个人订单详细信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<bool> My_Order(OrderGoodsModel item)
        {
            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess, "https://mobile.yangkeduo.com/order.html?order_sn=" +
                                                               item.OrderSn +
                                                               "&main_orders=1&refer_page_name=my_order&refer_page_id=&refer_page_sn=10032");
            if (await VerificationHanlder())
            {
                if (Program._Run_ != 1)
                {
                    return false;
                }

                goto Start;
            }

            if (await IsLogin())
            {
                item.OrderStatus = "账户掉线";
                Log("账户登陆失效");
                return false;
            }

            var rawData = await _currentPage.EvaluateExpressionAsync<string>("JSON.stringify(window.rawData)");
            if (string.IsNullOrEmpty(rawData) || rawData.Length < 15)
            {
                Log("订单详细为空:" + item.OrderSn);
                item.OrderStatus = "订单详细为空";
                return false;
            }

            var Json = JObject.Parse(rawData);
            item.LatestProgress = ((string)Json.SelectToken("data.express.timeLabel") ?? "") + " " +
                (string)Json.SelectToken("data.express.lastTrace") ?? "";
            if (item.LatestProgress.Contains("已签收") || item.LatestProgress.Contains("签收人"))
            {
                item.SigningTime = (string)Json.SelectToken("data.express.timeLabel") ?? "";
            }
            else
            {
                item.SigningTime = "";
            }

            item.LogisticsStatus = (string)Json.SelectToken("data.expressInfo.pddStatusDesc") ?? "";

            item.CreateTime =
                (string)Json.SelectToken("data.orderDescList")?.Where(w => ((string)w["key"]).Contains("下单时间"))
                    .FirstOrDefault()?["value"] ?? "";

            item.DeliveryTime =
                (string)Json.SelectToken("data.orderDescList")?.Where(w => ((string)w["key"]).Contains("发货时间"))
                    .FirstOrDefault()?["value"] ?? "";
            item.CourierName =
                (string)Json.SelectToken("data.orderDescList")?.Where(w => ((string)w["key"]).Contains("物流公司"))
                    .FirstOrDefault()?["value"] ?? "";
            item.CourierName =
                (string)Json.SelectToken("data.orderDescList")?.Where(w => ((string)w["key"]).Contains("物流公司"))
                    .FirstOrDefault()?["value"] ?? "";
            item.CourierNumber =
                (string)Json.SelectToken("data.orderDescList")?.Where(w => ((string)w["key"]).Contains("快递单号"))
                    .FirstOrDefault()?["value"] ?? "";

            item.Mobile = (string)Json.SelectToken("data.mobile") ?? "";
            item.ReceiveName = (string)Json.SelectToken("data.receiveName") ?? "";
            item.ProvinceName = (string)Json.SelectToken("data.provinceName") ?? "";
            item.CityName = (string)Json.SelectToken("data.cityName") ?? "";
            item.DistrictName = (string)Json.SelectToken("data.districtName") ?? "";
            item.ShippingAddress = (string)Json.SelectToken("data.shippingAddress") ?? "";
            Debug.WriteLine(item.goodsName + "----" + item.OrderStatus + "-----" + item.SkuSpec);
            return true;
        }

        /// <summary>
        ///     售后订单导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<AfterSaleModel>> AfterSaleOrderTask()
        {
            Log("进入订单列表");
            Start:
            //nav_tab_index 1待处理 0全部
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/complaint_list.html?refer_page_name=personal&refer_page_sn=10001&nav_tab_index=0&item_index=0&sp=0&is_back=0");

            if (await VerificationHanlder())
            {
                goto Start;
            }

            if (await IsLogin())
            {
                Log("账户登陆失效");
                return null;
            }

            var el = await _currentPage.MyGetXPathAndVisible("//span[contains(text(),'全部')]");
            if (el == null)
            {
                Log("切换导航失败");
                return null;
            }

            if (await el.MyClick())
            {
                WorkRandomSleep(1500, 2500);
            }

            //.as-list-page 
            var SelectorCssList = ".infinite-list-wrapper";
            el = await _currentPage.MyGetSelectorAndVisible(SelectorCssList);
            if (el == null)
            {
                if (!((await _currentPage.MyGetHtml()).Contains("待处理的") &&
                      (await _currentPage.MyGetHtml()).Contains("暂无")))
                {
                    Log("列表元素检测错误");
                    return null;
                }

                Log("售后列表为空,切换下个号码");
            }

            string isFinishLoading = null;
            var Itemi = 0;
            var SaleModels = new List<AfterSaleModel>();
            if (el == null)
            {
                return SaleModels;
            }

            do
            {
                isFinishLoading = await _currentPage.MyReact(SelectorCssList, "state.isFinishLoading");
                var list = await _currentPage.MyReact(SelectorCssList, "props.dataSource");

                if (!string.IsNullOrEmpty(list))
                {
                    var JsonList = JArray.Parse(list);
                    if (JsonList.Count > 0)
                    {
                        // File.WriteAllText("_LIST_",Convert.ToBase64String(Encoding.UTF8.GetBytes(await _Page_.MyReact(SelectorCssList, "state")+"\r\n------------------------\r\n"+ list)));
                        for (var i = Itemi; i < JsonList.Count; i++)
                        {
                            var m = new AfterSaleModel();

                            if (JsonList[i].SelectToken("listItemGoodsVo") != null)
                            {
                                //非正常加载
                                var navToDetailPageUrl =
                                    (string)JsonList[i].SelectToken("listItemExtraVo.navToDetailPageUrl");
                                if (!string.IsNullOrEmpty(navToDetailPageUrl))
                                {
                                    m.OrderSn = Regex.Match(navToDetailPageUrl, "order_sn=([0-9\\-]+)")?.Groups[1]
                                        .Value;
                                }

                                m.GoodsId = "";
                                m.goodsName = (string)JsonList[i].SelectToken("listItemGoodsVo.goodsName");
                                m.MallName = (string)JsonList[i].SelectToken("listItemMallVo.mallName");
                                m.OrderAmount =
                                    ((double)JsonList[i].SelectToken("listItemAmountVo.orderAmount") / 100.0)
                                    .ToString();
                                m.OrderStatus = (string)JsonList[i].SelectToken("listItemStatusVo.statusText");
                                m.afterSalesId = (string)JsonList[i].SelectToken("afterSalesId");
                                m.SkuSpec = (string)JsonList[i].SelectToken("listItemGoodsVo.spec");
                            }
                            else
                            {
                                //正常加载
                                m.OrderSn = (string)JsonList[i]["orderSn"];
                                m.GoodsId = (string)JsonList[i]["goodsId"];
                                m.goodsName = (string)JsonList[i]["goodsName"];
                                m.MallName = (string)JsonList[i]["mallName"];
                                m.OrderAmount = (string)JsonList[i]["orderAmountYuan"];
                                m.OrderStatus = (string)JsonList[i]["asStatusDesc"];
                                m.afterSalesId = (string)JsonList[i]["afterSalesId"];
                                m.SkuSpec = (string)JsonList[i]["spec"];
                            }

                            SaleModels.Add(m);
                            Itemi = i + 1;
                        }

                        var item = await _currentPage.QuerySelectorAllAsync(SelectorCssList + " .after-sale-list-item");
                        if (item != null && item.Length > 0)
                        {
                            await item.Last().MyScrollIntoView();
                        }
                    }
                }

                await _currentPage.MySelectorWheel(SelectorCssList, _random.Next(60, 150), 160);
                // await TaskHelper.Delay(1000);
                WorkRandomSleep(1000, 1100);
                if (InTimeHaveRequest())
                {
                    await _currentPage.MyWaitLoadingCompleted(ChromeProcess,
                        async () =>
                        {
                            await _currentPage.MySelectorWheel(SelectorCssList, _random.Next(60, 150), 160);
                        },
                        4 * 1000);
                }

                if ((await _currentPage.MyGetHtml()).Contains("您已经没有更多的订单了") ||
                    (await _currentPage.MyGetHtml()).Contains("您还没有相关的订单") ||
                    ((await _currentPage.MyGetHtml()).Contains("待处理的") &&
                     ((await _currentPage.MyGetHtml()).Contains("暂无") ||
                      (await _currentPage.MyGetHtml()).Contains("没有更多"))) ||
                    (await _currentPage.MyGetHtml()).Contains("退款/售后单了"))
                {
                    break;
                }

                if (Program._Run_ != 1)
                {
                    return null;
                }
            } while (isFinishLoading != null && isFinishLoading.Contains("false"));

            if (Program._Run_ != 1)
            {
                return null;
            }

            Log("售后列表获取共计:" + SaleModels.Count + "条");
            foreach (var item in SaleModels)
            {
                await Momplaint_Detail(item);
            }

            return SaleModels;
        }

        /// <summary>
        ///     售后订单详细
        /// </summary>
        /// <param name="Keys"></param>
        /// <returns></returns>
        public async Task<bool> Momplaint_Detail(AfterSaleModel item)
        {
            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/complaint_detail.html?order_sn=" +
                item.OrderSn +
                "&after_sales_id=" + item.afterSalesId + "&refer_page_name=complaint");
            if (await VerificationHanlder())
            {
                goto Start;
            }

            if (await IsLogin())
            {
                item.OrderStatus = "账户掉线";
                Log("账户登陆失效");
                return false;
            }

            var rawData = await _currentPage.EvaluateExpressionAsync<string>("JSON.stringify(window.rawData)");
            if (string.IsNullOrEmpty(rawData) || rawData.Length < 15)
            {
                Log("订单详细为空:" + item.OrderSn);
                item.OrderStatus = "订单详细为空";
                return false;
            }

            var Json = JObject.Parse(rawData);
            //退货地址详细
            item.ReturnAddress = (string)Json.SelectToken("store.detailData")
                ?.Where(w => (string)w["resourceTag"] == "mailOrderEntranceV2").FirstOrDefault()?.SelectToken("items")
                ?.Where(w => (string)w["resourceTag"] == "returnAddressV2").FirstOrDefault()
                ?.SelectToken("elements.buttons")?.Where(w => (string)w["text"] == "复制").FirstOrDefault()
                ?.SelectToken("event.copyValue");

            item.SqTime = (string)Json.SelectToken("store.detailData")
                ?.Where(w => (string)w["resourceTag"] == "afterSalesApplyInfoWithGoods").FirstOrDefault()
                ?.SelectToken("items")?.Where(w => (string)w["resourceTag"] == "afterSalesApplyInfoList")
                .FirstOrDefault()?.SelectToken("items")
                ?.Where(w =>
                    (string)w["resourceTag"] == "descWithOperation" &&
                    (string)w.SelectToken("elements.desc.prefix") == "申请时间").FirstOrDefault()
                ?.SelectToken("elements.desc.text");

            var afterSalesProcess = (string)Json.SelectToken("store.detailData")
                ?.Where(w => (string)w["resourceTag"] == "afterSalesProcess").FirstOrDefault()
                ?.SelectToken("elements.process")?.Where(w => (string)w["textColor"] == "#58595B").FirstOrDefault()
                ?.SelectToken("text");
            return true;
        }

        /// <summary>
        ///     add添加地址
        /// </summary>
        /// <param name="Keys"></param>
        /// <returns></returns>
        public async Task<bool> AddAddressTask(Dictionary<string, string> Keys)
        {
            Start:
            await _currentPage.MyGoToAsync(this.ChromeProcess,
                "https://mobile.yangkeduo.com/addresses.html?bind_phone_scene=personal_create_address&refer_page_name=personal");
            if (await VerificationHanlder())
            {
                if (Program._Run_ != 1)
                {
                    return false;
                }

                goto Start;
            }

            var ElXpath = "//*[contains(@data-active,\"red\")]//div[contains(text(),\"添加收货地址\")]";
            if (!await _currentPage.MyWaitXPath(ElXpath))
            {
                Log("收货地址添加:检测位置失败(0)");
                return false;
            }

            var El = await _currentPage.MyGetXPath(ElXpath);
            if (El == null)
            {
                Log("收货地址添加:检测位置失败(1)");
                return false;
            }

            WorkRandomSleep();
            await _currentPage.MyClick(El);
            WorkRandomSleep();
            if (await _currentPage.MyWaitSelector(".m-addr-title", async () => { await _currentPage.MyClick(El); }))
            {
                WorkRandomSleep(3000, 4000);
                try
                {
                    await _currentPage.MySelectorInputAndFocus("#name", Keys["收货人"]);
                    WorkRandomSleep();
                    await _currentPage.MySelectorInputAndFocus("#mobile", Keys["电话"]);
                    WorkRandomSleep();
                    await _currentPage.EvaluateExpressionHandleAsync(
                        "document.querySelector(\".m-addr-region-text\").click()");
                    WorkRandomSleep();


                    //   ElXpath = "//*[contains(@class,\"m-addr-region-text\")][contains(text(),\"点击选择\")]";
                    //El= await _Page_.MyGetXPath(ElXpath);
                    //   await _Page_.MyClick(El);
                    //WorkRandomSleep();
                    //await _Page_.MyClick(El);

                    var tryCount = 1;
                    var flag = false;
                    while (!await _currentPage.MyWaitSelector("#region-selector", async () =>
                           {
                               await _currentPage.EvaluateExpressionHandleAsync(
                                   "document.querySelector(\".m-addr-region-text\").click()");
                           }))
                    {
                        if (tryCount > 5)
                        {
                            flag = false;
                            break;
                        }

                        await _currentPage.EvaluateExpressionHandleAsync(
                            "document.querySelector(\".m-addr-region-text\").click()");
                        WorkRandomSleep();
                        tryCount++;
                        flag = true;
                    }

                    tryCount = 0;

                    if (!flag)
                    {
                    }


                    if (await _currentPage.MyWaitSelector("#region-selector", async () =>
                        {
                            await _currentPage.EvaluateExpressionHandleAsync(
                                "document.querySelector(\".m-addr-region-text\").click()");
                        }))
                    {
                        var _Start = DateTime.Now;
                        while (await _currentPage.MySelectorIsExistAndVisible("#region-selector"))
                        {
                            if ((DateTime.Now - _Start).TotalSeconds > 20)
                            {
                                Log("收货地址添加:选择地区超时!");
                                return false;
                            }

                            WorkRandomSleep();
                            var region = await _currentPage.QuerySelectorAsync("ul[id^='region-selector-list-']");

                            var id = await (await region.GetPropertyAsync("id")).JsonValueAsync() as string;
                            if (id.EndsWith("list-1"))
                            {
                                ElXpath = "//*[@id=\"" + id + "\"]/li[contains(.,\"" + Keys["省"] + "\")]";
                                await _currentPage.MyXpathClick(ElXpath);
                            }
                            else if (id.EndsWith("list-2"))
                            {
                                ElXpath = "//*[@id=\"" + id + "\"]/li[contains(.,\"" + Keys["市"] + "\")]";
                                await _currentPage.MyXpathClick(ElXpath);
                            }
                            else if (id.EndsWith("list-3"))
                            {
                                ElXpath = "//*[@id=\"" + id + "\"]/li[contains(.,\"" + Keys["区"] + "\")]";
                                await _currentPage.MyXpathClick(ElXpath);
                            }
                        }

                        await _currentPage.MySelectorInputAndFocus("#address", Keys["详细地址"]);
                        WorkRandomSleep();
                        await _currentPage.MySelectorClick(".m-addr-save-new.active");
                        WorkRandomSleep();
                        ElXpath = "//*[contains(@class,\"_1vGLmaHP\")]/li[contains(.,\"" + Keys["电话"] + "\")]";
                        if (await _currentPage.MyWaitXPath(ElXpath))
                        {
                            WorkRandomSleep();
                            ElXpath = "//*[contains(@class,\"_1vGLmaHP\")]/li[contains(.,\"" + Keys["电话"] +
                                      "\")]//span[contains(text(),\"默认\")]";
                            await _currentPage.MyXpathClick(ElXpath);
                            //  WorkRandomSleep(3000,5000);
                            WorkRandomSleep(1000, 1100);
                            if (InTimeHaveRequest())
                            {
                                await _currentPage.MyWaitLoadingCompleted(ChromeProcess,
                                    async () => { await _currentPage.MyXpathClick(ElXpath); });
                            }

                            Log("添加收货地址成功");
                            return true;
                        }

                        Log("等待目标地址出现超时");
                    }
                    else
                    {
                        Log("等待地区选择框超时");
                    }
                }
                catch (Exception ex)
                {
                    Log("收货地址添加:执行异常" + ex.Message);
                }
            }
            else
            {
                Log("收货地址添加:检测位置失败(2)");
            }

            return false;
        }

        /// <summary>
        ///     下单
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Skus"></param>
        public async Task<string> DownOrder(string Url, string[] Skus)
        {
            for (var i = 0; i < Skus.Length; i++)
            {
                //将特殊的标记还原
                Skus[i] = Skus[i].Replace("(火火火)", string.Empty);
            }

            Log("进入商品页");
            Satrt:
            await _currentPage.MyGoToAsync(this.ChromeProcess, Url);
            if ((await _currentPage.MyGetHtml()).Contains(">原商品已售罄"))
            {
                return "原商品已售罄";
            }

            if (await VerificationHanlder())
            {
                if (Program._Run_ != 1)
                {
                    return "软件停止";
                }

                goto Satrt;
            }

            if (!(await _currentPage.MyGetHtml()).Contains(">进店逛逛<"))
            {
                return "进入店铺失败";
                //SwitchWebFProxy();
                //goto start;
            }
            //if (_Run != 1)
            //{
            //    return "任务停止";
            //}

            //Qzax7E1w 发起拼单按钮选择SKU跳转到立即支付页面
            //_1N7qt2Rt  发起拼单字体那
            WorkRandomSleep(2000, 4000);
            if (await _currentPage.MyWaitSelector(".Qzax7E1w:last-of-type", null))
            {
                var el = await _currentPage.MyGetSelectorAndVisible("[aria-label='关闭对话框']");
                if (el != null)
                {
                    await el.MyClick();
                    WorkRandomSleep();
                }

                el = await _currentPage.MyGetSelectorAndVisible("[aria-label='关闭按钮']");
                if (el != null)
                {
                    await el.MyClick();
                    WorkRandomSleep();
                }

                Debug.WriteLine("存在");
                el = await _currentPage.QuerySelectorAsync(".Qzax7E1w:last-of-type ._1N7qt2Rt");
                if (el != null)
                {
                    await el.MyScrollIntoView();
                    WorkRandomSleep();
                }

                for (var i = 0; i < 3; i++)
                {
                    await _currentPage.MySelectorClick(".Qzax7E1w:last-of-type ._1N7qt2Rt");
                    if (await _currentPage.MyWaitSelector("div[aria-modal='true'][class='_2Aq-Ugkh']",
                            async () => { await _currentPage.MySelectorClick(".Qzax7E1w:last-of-type ._1N7qt2Rt"); },
                            3))
                    {
                        break;
                    }
                }

                //2Aq-Ugkh 弹出SKU
                if (await _currentPage.MyWaitSelector("div[aria-modal='true'][class='_2Aq-Ugkh']",
                        async () => { await _currentPage.MySelectorClick(".Qzax7E1w:last-of-type ._1N7qt2Rt"); }, 2))
                {
                    Log("选择SKU下单:" + string.Join("/", Skus));
                    WorkRandomSleep(1000, 2000);
                    foreach (var Sku in Skus)
                    {
                        //弹出层//按钮
                        var querySelector = "._2Aq-Ugkh div [aria-label='" + Sku + "']";

                        if (!await _currentPage.MySelectorIsExist(querySelector))
                        {
                            Debug.WriteLine("Sku找不到:" + Sku);
                            return "Sku找不到:" + Sku;
                        }

                        var El = await _currentPage.QuerySelectorAsync(querySelector);
                        var className = await El.GetPropertyAsync("className");
                        //_2bBCR7qt 已经选中sku
                        if (!className.ToString().Contains("_2bBCR7qt"))
                        {
                            await El.MyScrollIntoView();
                            await _currentPage.MySelectorClick(querySelector);
                            WorkRandomSleep();
                        }
                        else
                        {
                            Debug.WriteLine("已经选中");
                        }
                    }

                    WorkRandomSleep(1500, 2000);
                    await _currentPage.MySelectorClick("._2Aq-Ugkh [aria-label='确定']");
                    WorkRandomSleep(1000, 1100);
                    if (InTimeHaveRequest())
                    {
                        await _currentPage.MyWaitLoadingCompleted(ChromeProcess,
                            async () => { await _currentPage.MySelectorClick("._2Aq-Ugkh [aria-label='确定']"); });
                    }

                    if (!await _currentPage.MyWaitXPath("//div[@aria-label=\"立即支付\"]"))
                    {
                        return "跳转下单页面失败";
                    }

                    Log("下单页面");
                    return "OK";
                }

                return "弹出Sku选择失败";
            }

            return "检测不到拼单按钮";
            //跳转页面异常
        }

        /// <summary>
        ///     优惠卷切换
        /// </summary>
        /// <returns></returns>
        public async Task<bool> PromotionReceive()
        {
            //  var region = await _Page_.QuerySelectorAsync("ul[id^='region-selector-list-']");
            // string id = await(await region.GetPropertyAsync("id")).JsonValueAsync() as string;
            var XPath = "//div/span[contains(.,\"店铺优惠\")]/..";
            //优惠卷弹出框关闭按钮
            var _CloseSelector = ".JcYj4LFb [aria-label='关闭']";
            var el = await _currentPage.MyGetXPath(XPath);
            if (el != null)
            {
                var textContent = await el.MyTextContent();
                if (textContent.Contains("领关注券可减") || textContent.Contains("领直播券可减"))
                {
                    Log("优惠卷领取");
                    await el.MyScrollIntoView();
                    WorkRandomSleep(2000, 4500);
                    if (textContent.Contains("领关注券可减"))
                    {
                        await _currentPage.MyClick(el);
                        WorkRandomSleep();
                        if (await _currentPage.MyWaitSelector(_CloseSelector,
                                async () => { await _currentPage.MyClick(el); }))
                        {
                            WorkRandomSleep();
                            XPath = "//*[@id=\"shop-promotion-list\"]//div[contains(text(),\"关注并领取\")]";
                            el = await _currentPage.MyGetXPath(XPath);
                            if (el != null)
                            {
                                await _currentPage.MyClick(el);
                                WorkRandomSleep();
                                XPath = "//*[@data-active=\"red\"][contains(text(),\"关注并领取\")]";
                                el = await _currentPage.MyGetXPath(XPath);
                                if (el != null)
                                {
                                    await _currentPage.MyClick(el);
                                    WorkRandomSleep();
                                }
                            }
                        }
                        else
                        {
                            Log("未打开优惠卷列表");
                        }
                    }
                    else if (textContent.Contains("领直播券可减"))
                    {
                        await _currentPage.MyClick(el);
                        WorkRandomSleep();
                        if (await _currentPage.MyWaitSelector(_CloseSelector,
                                async () => { await _currentPage.MyClick(el); }))
                        {
                            WorkRandomSleep();
                            XPath = "//*[@id=\"shop-promotion-list\"]//div[contains(text(),\"领取\")]";
                            el = await _currentPage.MyGetXPath(XPath);
                            if (el != null)
                            {
                                await _currentPage.MyClick(el);
                                WorkRandomSleep();
                                XPath = "//*[@data-active=\"red\"][contains(text(),\"领取\")]";
                                el = await _currentPage.MyGetXPath(XPath);
                                if (el != null)
                                {
                                    await _currentPage.MyClick(el);
                                    WorkRandomSleep();
                                }
                            }
                        }
                        else
                        {
                            Log("未打开优惠卷列表");
                        }
                        //brower1.ExecuteJavaScript("_cefjs_(\"div>span:contains('店铺优惠)\").parent().click()");
                        //await TaskHelper.Delay(1500);
                        //brower1.ExecuteJavaScript("_cefjs_(\"#shop-promotion-list div:contains('领取)\").last().click()");
                        //await TaskHelper.Delay(1500);
                        //brower1.ExecuteJavaScript("_cefjs_(\"div[data-active=red]:contains('领取)\").last().click()");
                    }

                    WorkRandomSleep(3000, 4000);
                    //领取成功后的关闭按钮
                    if (await _currentPage.MySelectorClick("._1CURM0O1"))
                    {
                        WorkRandomSleep();
                    }

                    if (await _currentPage.MySelectorClick(_CloseSelector))
                    {
                        WorkRandomSleep();
                    }

                    return true;
                }
            }

            //string title = brower1.EvaluateScriptString("_cefjs_(\"div>span:contains('店铺优惠)\").parent().text()");

            return false;
        }

        /// <summary>
        ///     拼多多下单页面检测支付
        /// </summary>
        /// <returns></returns>
        public async Task<bool> OrderPayment(double Price)
        {
            WorkRandomSleep(3000, 4000);
            if (await PromotionReceive())
            {
                WorkRandomSleep(3000, 4000);
            }

            Satrt:
            if (await VerificationHanlder())
            {
                if (Program._Run_ != 1)
                {
                    return false;
                }

                goto Satrt;
            }

            var XPath = "//div/span/i[contains(text(),\"¥\")]/..";
            var el = await _currentPage.MyGetXPath(XPath);
            if (el == null)
            {
                //价格获取失败
                return false;
            }

            var textContent = await el.MyTextContent();
            textContent = textContent.Replace("¥", "").Trim();
            if (double.Parse(textContent) != Price)
            {
                Log("商品价格对比错误");
                // return false;
            }

            XPath = "//div/span[contains(.,\"支付宝\")]/../..";
            el = await _currentPage.MyGetXPath(XPath);
            if (el == null)
            {
                //支付宝付款方式失败
                return false;
            }

            await el.MyScrollIntoView();
            await _currentPage.MyClick(el);
            WorkRandomSleep();
            await el.MyClick((w, h) => { return new Offset(w - 50, h - 50); });
            WorkRandomSleep();
            XPath = "//div[@aria-label=\"立即支付\"]";
            el = await _currentPage.MyGetXPath(XPath);
            if (el == null)
            {
                //立即付款失败
                return false;
            }

            await _currentPage.MyClick(el);
            // WorkRandomSleep();
            WorkRandomSleep(1000, 1100);
            if (InTimeHaveRequest())
            {
                await _currentPage.MyWaitLoadingCompleted(ChromeProcess,
                    async () => { await _currentPage.MyClick(el); });
            }

            return _currentPage.Url.Contains(".alipay.");
        }

        /// <summary>
        ///     支付宝付款
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AlipayPayment(bool Login = false, string LoginUser = null, string Pass = null)
        {
            Log("支付宝页面");
            var alipayRes = "";
            var IsSubmitPay = false;
            WorkRandomSleep(2000, 3000);
            var _start = DateTime.Now;
            while (string.IsNullOrEmpty(alipayRes))
            {
                if ((DateTime.Now - _start).TotalMinutes > 3)
                {
                    alipayRes = "支付宝超时!";
                    break;
                }

                var Html = await _currentPage.MyGetHtml();
                var dialogText = Regex
                    .Match(Html ?? "", "<div class=\"am-dialog-text\" style=\"text-align:center;\">(.+?)</div>")
                    ?.Groups[1]?.Value;
                if (!string.IsNullOrEmpty(dialogText))
                {
                    alipayRes = dialogText;
                    await TaskHelper.Delay(500);
                    break;
                }

                if (Html.Contains("继续浏览器付款"))
                {
                    await _currentPage.MySelectorClick("div.J-h5Pay");
                }
                else if (Html.Contains(">支付密码登录</a>") || Html.Contains(">请输入支付宝账号</a>"))
                {
                    await _currentPage.MySelectorClick("a[seed=v5_need_phonelogin-login]");
                    Debug.WriteLine("未登录");
                    await TaskHelper.Delay(2000);
                }
                else if (Html.Contains("请输入支付宝账号"))
                {
                    if (Login)
                    {
                        WorkRandomSleep();
                        Log("自动登录支付宝");
                        await _currentPage.MySelectorInputAndFocus("#logon_id", LoginUser);
                        WorkRandomSleep();
                        await _currentPage.MySelectorClick("span[data-ctype=spwd]");
                        WorkRandomSleep();
                        await _currentPage.MySelectorInputAndFocusAndRetry("#pwd_unencrypt.J-pwd-long", Pass);
                        WorkRandomSleep();
                        await _currentPage.MySelectorClick("button[seed=v5_need_login_new-submit]");
                        WorkRandomSleep();
                    }
                }
                else if (Html.Contains("<h4>输入支付密码</h4>"))
                {
                    if (!IsSubmitPay)
                    {
                        WorkRandomSleep();
                        if (Html.Contains("请输入验证码"))
                        {
                            alipayRes = "支付需要验证码";
                            await TaskHelper.Delay(100);
                            //  break;
                        }

                        Log("输入支付密码");
                        if (!string.IsNullOrEmpty(Pass))
                        {
                            var El = await _currentPage.MyGetSelectorAndVisible("#pwd_unencrypt.J-pwd-long");
                            if (El != null)
                            {
                                await El.MyInputAndFocus(Pass);
                                IsSubmitPay = true;
                                WorkRandomSleep();
                            }

                            El = await _currentPage.MyGetSelectorAndVisible("#spwd");
                            if (El != null)
                            {
                                await El.MyInputAndFocus(Pass);
                                IsSubmitPay = true;
                                WorkRandomSleep();
                            }

                            El = await _currentPage.MyGetSelectorAndVisible("#pwd");
                            if (El != null)
                            {
                                await El.MyInputAndFocus(Pass);
                                IsSubmitPay = true;
                                WorkRandomSleep();
                            }
                        }
                    }

                    if (await _currentPage.MyGetSelectorAndVisible("button.am-button.v2020v2-button[type='submit']") !=
                        null)
                    {
                        //确定按钮
                        var El = await _currentPage.MyGetSelectorAndVisible(
                            "button.am-button.v2020v2-button[type='submit']");
                        if (El != null)
                        {
                            await _currentPage.MyClick(El);
                        }

                        WorkRandomSleep();
                    }
                    else if (Html.Contains("v5_cashier_pre_confirm-submit"))
                    {
                        //确认付款按钮
                        var El = await _currentPage.MyGetSelectorAndVisible(
                            "button[seed=v5_cashier_pre_confirm-submit]");
                        if (El != null)
                        {
                            await _currentPage.MyClick(El);
                        }

                        WorkRandomSleep();
                    }
                }
                else if (Html.Contains("v5_cashier_pre_confirm-submit"))
                {
                    //确认付款按钮
                    var El = await _currentPage.MyGetSelectorAndVisible("button[seed=v5_cashier_pre_confirm-submit]");
                    if (El != null)
                    {
                        await _currentPage.MyClick(El);
                    }

                    WorkRandomSleep();
                }
                else if (Html.Contains(">支付成功</h4>"))
                {
                    alipayRes = "OK";
                    await TaskHelper.Delay(500);
                    break;
                }
                else if (Html.Contains(">出错了<"))
                {
                    alipayRes = "出错了";
                    await TaskHelper.Delay(500);
                    break;
                }
                else
                {
                    var El = await _currentPage.MyGetSelectorAndVisible(".am-act-success");
                    if (El != null)
                    {
                        if ((await El.MyTextContent() ?? "").Contains("付款成功"))
                        {
                            alipayRes = "OK";
                            await TaskHelper.Delay(500);
                            break;
                        }
                    }
                }

                await _currentPage.MyWaitLoadingCompleted(null, null, 4 * 1000);
            }

            Log("支付结果:" + alipayRes);
            Debug.WriteLine(alipayRes);
            if (alipayRes == "OK")
            {
                if (await _currentPage.MySelectorClick("a.am-header-operate"))
                {
                    WorkRandomSleep(3000, 4000);
                }
            }

            return alipayRes == "OK";
        }

        /// <summary>
        ///     自动保存Cookies
        /// </summary>
        /// <returns></returns>
        public async Task<bool> AutoSaveCookies()
        {
            var cookies = await GetPddCookies();
            if (!string.IsNullOrEmpty(cookies))
            {
                File.WriteAllText(
                    Path.Combine(AppClass.GetChromeDataPath(ItemModel.ChromeData), "_MyCookies_"), cookies);
                return true;
            }

            return false;
        }

        /// <summary>
        ///     自动恢复Cookies
        /// </summary>
        /// <returns></returns>
        public async Task AutoSetCookies()
        {
            var cookiesPath =
                Path.Combine(AppClass.GetChromeDataPath(ItemModel.ChromeData), "_MyCookies_");
            if (File.Exists(cookiesPath))
            {
                var _cookies = File.ReadAllText(cookiesPath);
                await SetPddCookies(_cookies);
                Log("恢复Cookies完毕");
            }
            else
            {
                Log("本地没有Cookies恢复文件");
            }
        }

        /// <summary>
        ///     如果目标不符合或者cookie中不包含padd
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetPddCookies()
        {
            try
            {
                if (_currentPage.Url.Contains("yangkeduo.com") && !_currentPage.Url.Contains("login.html"))
                {
                    var cookie = await _currentPage.EvaluateExpressionAsync<string>("document.cookie");

                    if (!string.IsNullOrEmpty(HttpHelper.CookiesVal(cookie, "PDDAccessToken")))
                    {
                        return cookie;
                    }
                }
            }
            catch (Exception)
            {
            }


            return null;
        }

        /// <summary>
        ///     设置Cookie
        /// </summary>
        /// <param name="Cookies"></param>
        /// <returns></returns>
        public async Task SetPddCookies(string Cookies)
        {
            await _currentPage.MyGoToAsync(this.ChromeProcess, "https://mobile.yangkeduo.com/");
            await TaskHelper.Delay(1000 * 5);
            try
            {
                var MySetCookieStr =
                    "function $MySetCookie(key, value, days) {\r\n  var date = new Date();\r\n  days = days || 365;\r\n  date.setTime(+date + days * 86400000); //24 * 60 * 60 * 1000\r\n  window.document.cookie =\r\n    key + \"=\" + value + \"; expires=\" + date.toUTCString() + \"; path=/; domain=.yangkeduo.com\";\r\n  return value;\r\n};";
                var KeyVal = HttpHelper.CookiesToKeyValue(Cookies);
                var SetCookie = "";
                foreach (var item in KeyVal)
                {
                    if (item.Key == "PDDAccessToken")
                    {
                        SetCookie += "$MySetCookie(\"" + item.Key + "\",\"" + item.Value + "\",365*20);\r\n";
                    }
                }

                Debug.WriteLine(SetCookie);
                await _currentPage.EvaluateExpressionHandleAsync(MySetCookieStr + SetCookie);
            }
            catch (Exception ex)
            {
                Log("Cookies异常:" + ex.Message);
            }

            Debug.WriteLine("准备刷新");
            await TaskHelper.Delay(1000);
            await _currentPage.ReloadAsync();
            await TaskHelper.Delay(1000);
        }
    }
}